﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CuteSprite.Eme.Data.CRM;
using CuteSprite.Eme.Data.Settlement;
using HmFramework.Data;
using HmFramework.Net;
using HmFramework.Net.Monitoring;
using HmFramework.Text;
using HmFramework.Xml;

namespace CuteSprite.Eme.MIS.Server
{
	/// <summary>BsdMis server session.</summary>
	public partial class BsdMisSession
	{
		#region -- method GrantExpressStaff --

		/// <summary>保存快件收件、派件员工信息</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void GrantExpressStaff(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 4)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 GrantExpressStaff <expressCategory> <isRecipient> <ExpressID> <StaffID1,StaffID2><CRLF>");
					return;
				}
				var category = (ExpressBusinessCategory)Convert.ToInt32(args[0]);
				var flag = Convert.ToInt32(args[1]);

				switch (category)
				{
					case ExpressBusinessCategory.ExpressOCS:
						if (flag > 0)
						{
							ExpressRecipient.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						else
						{
							ExpressSend.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						break;
					case ExpressBusinessCategory.ExpressEconomyLine:
						if (flag > 0)
						{
							ExpressEconomyLineRecipient.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						else
						{
							ExpressEconomyLineSend.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						break;
					case ExpressBusinessCategory.ExpressMix:
						if (flag > 0)
						{
							ExpressMixRecipient.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						else
						{
							ExpressMixSend.GrantAll(Convert.ToInt32(args[2]), StringHelper.UnQuoteString(args[3]), CurrentUser);
						}
						break;

					default:
						break;
				}

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "GrantExpressStaff completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method GetExpressStaff --

		/// <summary>保存快件收件、派件员工信息</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void GetExpressStaff(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 3)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 GetExpressStaff <expressCategory> <isRecipient> <ExpressID><CRLF>");
					return;
				}
				var category = (ExpressBusinessCategory)Convert.ToInt32(args[0]);
				var flag = Convert.ToInt32(args[1]);
				var expressID = Convert.ToInt32(args[2]);

				String ids = null;
				switch (category)
				{
					// OCS专线
					case ExpressBusinessCategory.ExpressOCS:
						if (flag > 0)
						{
							var list = ExpressRecipient.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						else
						{
							var list = ExpressSend.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						break;
					//富力经济线
					case ExpressBusinessCategory.ExpressEconomyLine:
						if (flag > 0)
						{
							var list = ExpressEconomyLineRecipient.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						else
						{
							var list = ExpressEconomyLineSend.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						break;
					// 富力通
					case ExpressBusinessCategory.ExpressMix:
						if (flag > 0)
						{
							var list = ExpressMixRecipient.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						else
						{
							var list = ExpressMixSend.FindAllByExpressID(expressID);
							if (list != null && list.Count > 0)
							{
								ids = String.Join(",", list.ToList().Select(e => e.StaffID).ToList().ConvertAll(e => "" + e).ToArray());
							}
						}
						break;
					default:
						break;
				}

				SendResponseAsync(new UntaggedResponseEntityFieldValue(ids));

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "GetExpressStaff completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method BatchUpdateExpressStatus --

		/// <summary>批量自动添加指定的快件操作状态</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void BatchUpdateExpressStatus(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 2)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 BatchUpdateExpressStatus <0> <0><CRLF>");
					return;
				}
				var os = (ExpressOperationStatus)Convert.ToInt32(args[0]);
				var isEconomyLine = Convert.ToInt32(args[1]) != 0;

				if (!isEconomyLine)
				{
					ExpressStatus.BatchUpdateStatus(os, CurrentUser);
				}
				else
				{
					ExpressEconomyLineStatus.BatchUpdateStatus(os, CurrentUser);
				}

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "BatchUpdateExpressStatus completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method BatchUpdateExpressOperationStatus --

		/// <summary>批量更新快件操作状态</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void BatchUpdateExpressOperationStatus(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', true);
				if (args.Length != 4)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 BatchUpdateExpressOperationStatus <ids> <opTime> <opdesc> <0><CRLF>");
					return;
				}

				var isEconomyLine = Convert.ToInt32(args[3]) != 0;
				if (!isEconomyLine)
				{
					ExpressStatus.BatchUpdateStatus(args[0], args[1], args[2], CurrentUser);
				}
				else
				{
					ExpressEconomyLineStatus.BatchUpdateStatus(args[0], args[1], args[2], CurrentUser);
				}

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "BatchUpdateExpressOperationStatus completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method GetExpressLastStatus --

		/// <summary>获取快件最新状态</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void GetExpressLastStatus(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 2)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 GetExpressLastStatus <ExpressID> <0><CRLF>");
					return;
				}
				var expressid = Convert.ToInt32(args[0]);
				var isEconomyLine = Convert.ToInt32(args[1]) != 0;

				MemoryStream ms = null;
				IEntity entity = null;
				if (!isEconomyLine)
				{
					entity = ExpressStatus.FindLastStatusByExpressMixID(expressid);
				}
				else
				{
					entity = ExpressEconomyLineStatus.FindLastStatusByExpressMixID(expressid);
				}
				UntaggedResponseEntity ur;
				if (entity != null)
				{
					// xml序列化实体
					var buffs = Encoding.UTF8.GetBytes(entity.ToXml());
					if (GZipEnabled)
					{
						ms = NetHelper.CompressStream(new MemoryStream(buffs));
					}
					else
					{
						ms = new MemoryStream(buffs);
					}
					ur = new UntaggedResponseEntity(ms.Length, GZipEnabled);
				}
				else
				{
					ur = new UntaggedResponseEntity(0, GZipEnabled);
				}

				SendResponseAsync(ur);
				if (ms != null) { SendResponseAsync(new UntaggedResponseStream(ms)); }

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "GetExpressLastStatus completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method CheckExpressExist --

		/// <summary>检查快件运单号码是否已存在</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void CheckExpressExist(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 3)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 CheckExpressExist <0> <ExpressNo> <ExpressID><CRLF>");
					return;
				}

				var isExist = false;
				var category = (ExpressBusinessCategory)Convert.ToInt32(args[0]);
				switch (category)
				{
					case ExpressBusinessCategory.ExpressOCS:
						isExist = Express.CheckExpressNoIsExist(StringHelper.UnQuoteString(args[1]), Convert.ToInt32(args[2]));
						break;
					case ExpressBusinessCategory.ExpressMix:
						isExist = ExpressMix.CheckExpressNoIsExist(StringHelper.UnQuoteString(args[1]), Convert.ToInt32(args[2]));
						break;
					case ExpressBusinessCategory.ExpressEconomyLine:
						isExist = ExpressEconomyLine.CheckExpressNoIsExist(StringHelper.UnQuoteString(args[1]), Convert.ToInt32(args[2]));
						break;
					default:
						break;
				}

				SendResponseAsync(new UntaggedResponseEntityFieldValue(isExist ? 1 : 0));

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "CheckExpressExist completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method BatchUpdateSettlements --

		/// <summary>根据日期范围批量自动更新结算记录</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void BatchUpdateSettlements(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', true);
				if (args.Length != 2)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 BatchUpdateSettlements <startdate> <enddate><CRLF>");
					return;
				}

				DateTime startDate;
				DateTime endDate;
				if (DateTime.TryParse(args[0], out startDate) && DateTime.TryParse(args[1], out endDate))
				{
					// TODO
					Settlement.BatchGenerateSettlement(startDate, endDate);
					SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "BatchUpdateSettlements completed in {0}".FormatWith(ElapsedTime)));
				}
				else
				{
					SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "无法解析日期范围参数"));
				}
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method MakeExpressNextNo --

		/// <summary>自动产生运单号码</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void MakeExpressNextNo(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', false);
				if (args.Length != 1)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 MakeExpressNextNo <0><CRLF>");
					return;
				}

				var expressno = DiscardedExpressNo.MakeExpressNextNo((ExpressBusinessCategory)Convert.ToInt32(args[0]));

				SendResponseAsync(new UntaggedResponseEntityFieldValue(expressno));

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "MakeExpressNextNo completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion

		#region -- method BatchUpdateCustomerSelfStatus --

		/// <summary>批量更改用户自主下单记录的已揽件状态</summary>
		/// <param name="cmdTag"></param>
		/// <param name="cmdText"></param>
		private void BatchUpdateCustomerSelfStatus(String cmdTag, String cmdText)
		{
			if (!IsAuthenticated)
			{
				SendResponseAsync(new ResponseServerStatus(cmdTag, "NO", "Authentication required."));
				return;
			}
			try
			{
				StartWatch();

				String[] args = StringHelper.SplitQuotedString(cmdText, ' ', true);
				if (args.Length != 1)
				{
					SendBadResponseServerStatus(cmdTag, "Invalid arguments. Syntax: 00001 BatchUpdateCustomerSelfStatus <ids><CRLF>");
					return;
				}

				ExpressMix.BatchUpdateCustomerSelfStatus(args[0], CurrentUser);

				SendResponseAsync(new ResponseServerStatus(cmdTag, "OK", "BatchUpdateCustomerSelfStatus completed in {0}".FormatWith(ElapsedTime)));
			}
			catch (Exception ex) { OnError(ex, cmdTag); }
		}

		#endregion
	}
}
